// 导入数据库操作模块
const db = require('../db/index');
// 导入请求模块
const request = require('request');
const { response } = require('express');

// 登录的处理函数
exports.login = (req, res) => {
    const js_code = req.body.js_code;
    console.log(req.body);
    request({
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx03079661965a3a75&secret=b7a36b167df93156a0be6a50cc43e348&js_code=${js_code}&grant_type=authorization_code`
    }, (err, response, data) => {
        if (err) {
            return res.send({ status: "获取openid失败", message: err.message });
        }
        const output = JSON.parse(data);
        console.log("登录的信息： ", output)
        const openid = output.openid;
        console.log("登录的openid: ", openid);
        const sqlStr = `select * from user where id= ? ;`;
        db.query(sqlStr, [openid], function (err, results) {
            if (results.length == 0) {
                return res.send({ status: "用户不存在，请注册" });
            }
            if (err) {
                return res.send({ status: "登录失败", message: err.message });
            }
            if (results.length == 1) {
                return res.send(results);
            }

        });
    })
}

// 注册的处理函数
exports.register = (req, res) => {
    const js_code = req.body.js_code;
    const data = req.body;
    const name = data.name;
    const img = JSON.parse(data.img);
    console.log(req.body);
    request({
        url: `https://api.weixin.qq.com/sns/jscode2session?appid=wx03079661965a3a75&secret=b7a36b167df93156a0be6a50cc43e348&js_code=${js_code}&grant_type=authorization_code`
    }, (err, response, data) => {
        if (err) {
            return res.send({ status: "获取openid失败", message: err.message });
        }
        const output = JSON.parse(data);
        const openid = output.openid;
        console.log("######注册 start######")
        console.log("data", output);
        console.log("openid", openid);
        console.log("######注册 end######")
        const sqlStr = `insert into user( id , name , img ) 
                        values (?,?,?)`;
        const sqlImg = `insert into user_img(id,user_id,img) values (?,?,?)`;
        db.query(sqlStr, [openid, name, img[0]], function (err, results) {
            console.log("result1: ", results);
            if (err) {
                return res.send({ status: "添加失败", message: err.message });
            } else {
                const id2 = "userimg" + new Date().getTime();
                db.query(sqlImg, [id2, openid, img[0]], function (err, results) {
                    console.log("result2: ", results);
                    if (err) {
                        return res.send({ status: "图片添加失败", message: err.message })
                    }
                })
            }
        });
        return res.send({ openid: output.openid });
    })
}
